package com.gitee.feizns.explore.data_structure.linked_list.singly.rotate;

/**
 * @author feizns
 * @since 2019/10/10
 */
public class RotateRightMain {

    public static void main(String[] args) {
        ListNode node = create();
        rotateRight(node, 0).print();
    }

    public static ListNode rotateRight(ListNode head, int k) {
        if ( head != null ) {
            int len = len(head);
            k = k % len;
            if ( k != 0 ) {
                ListNode node = node(len - 1 - k , head);
                ListNode newHead = node.next;
                ListNode last = node(len - 1, head);
                last.next = head;
                node.next = null;
                return newHead;
            }
        }
        return head;
    }

    public static int len(ListNode head) {
        int i = 0;
        for (; head != null; head = head.next, i++) {}
        return i;
    }

    public static ListNode node(int index, ListNode head) {
        for (int i = 0; i < index; i++)
            head = head.next;
        return head;
    }

    public static ListNode create() {
        ListNode node = new ListNode(1);
        node.next = new ListNode(2);
        node.next.next = new ListNode(3);
        return node;
    }

}
